<template>
  <el-card>
    <el-form :model="form" inline>
      <el-row>
        <el-col :span="4">
          <el-form-item label="账号名：">
            <el-input v-model="form.username" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="账号角色：">
            <el-select v-model="form.level" placeholder="请选择角色" style="width: 180px;" >
              <el-option
                  v-for="item in roleMap"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          </el-col>
        <el-col :span="6">
        <el-form-item label="账号状态：">
          <el-select v-model="form.state" placeholder="请选择状态" style="width: 150px;">
            <el-option
                v-for="item in stateMap"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="6">
        <el-form-item >
          <el-button type="primary" @click="searchleaderList">查询</el-button>
          <el-button @click="form.level='';form.username='';form.state=''">重置</el-button>
        </el-form-item>
        </el-col>
      </el-row>
        <el-row>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer = true">添加系统账号</el-button>
        </div>
        </el-row>
    </el-form>
  </el-card>

  <el-card style="height: 400px; margin-top: 20px">
  <!-- 用户管理列表 -->
  <div class="table-container" style="display: flex; flex-direction: column;">
    <el-table :data="tableData" stripe border class="center-table" style="margin-top:20px;">
      <el-table-column prop="leaderid" label="序号" width="100" />
      <el-table-column prop="username" label="账号名" width="180"/>
      <el-table-column prop="password" label="账号密码" width="180"/>
      <el-table-column prop="level" label="账号角色" width="200">
        <template #default="{ row }">
          {{ formatLevel(row.level) }}
        </template>
      </el-table-column>
      <el-table-column prop="state" label="账号状态" width="200">
        <template #default="{ row }">
<!--          <el-switch
              v-model="row.state"
              :active-value="0"
              :inactive-value="1"
              @change="handleChangeStatus(row, $event)"
          />-->
          {{ formatState(row.state) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" >
          <template #default="scope">
            <el-button :icon="Edit"  type="primary" @click="update(scope.$index,scope.row)"></el-button>
            <el-popconfirm title="确认删除?" @confirm="delLeader">
              <template #reference>
                <el-button :icon="Delete"  type="danger" @click="del(scope.$index,scope.row)"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
    </el-table>
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" title="添加账号" direction="rtl" size="23%">
      <el-form :model="leaderModel" label-width="100px">
        <el-form-item label="账号名:">
          <el-input v-model="leaderModel.username" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="账号密码:">
          <el-input v-model="leaderModel.password" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="账号角色:" >
          <el-select v-model="leaderModel.level"  placeholder="请选择角色" style="width: 180px;">
            <el-option
                v-for="item in roleMap"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态:">
          <el-select v-model="leaderModel.state" placeholder="请选择" :disabled="true">
            <el-option
                v-for="item in stateMap"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addleader('提交')">提交</el-button>
          <el-button type="info" @click="no('取消')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-dialog v-model="dialogFormVisible" title="账号信息编辑" width="500">
      <el-form :model="form1">
        <el-form-item label="账号名:">
          <el-input v-model="form1.username" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="账号密码:">
          <el-input v-model="form1.password" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="账号角色:">
          <el-select v-model="form1.level" placeholder="请选择角色" style="width: 180px;">
            <el-option
                v-for="item in roleMap"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
            </el-select>
        </el-form-item>
        <el-form-item label="账号状态:">
          <el-select v-model="form1.state" placeholder="请选择状态">
            <el-option
                v-for="item in stateMap"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateleader">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分页条 -->
    <div class="page" style="display: flex; justify-content: flex-end;">
      <el-pagination
          :background=true
          v-model:total="totalCount"
          v-model:page-size="form.pageSize"
          :small=false
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          layout="sizes, prev, pager, next, jumper"
          @current-change="changePageNumber" />
    </div>
  </div>
  </el-card>
</template>

<script setup>
//导包
import {reactive, ref,onMounted,watch} from 'vue'
import villageData from '@/assets/village.json';
import {
  searchleader,
  leaderAddService,
  leaderDelService,
  leaderUpdateService
} from '@/api/leader'
import { ElMessage } from 'element-plus'
import {Delete, Edit} from "@element-plus/icons-vue";

//表格初始化
const form = reactive({
  username:'',
  password: '',
  level: '',
  state: '',
  pageNum: 1,
  pageSize: 5
})

//添加表单
const leaderModel = ref({
  username:' ',
  password:'',
  level:' ',
  state:0,
})

const tableData = ref([]);
const dialogVisible = ref(false);
var requestData=ref([]);

//查询
const searchleaderList = async () => {
  try {
    // 构建请求参数对象，包含表单中的筛选条件
    const queryParams = {
      pageNum: form.pageNum,
      pageSize: form.pageSize,
      username: form.username.trim(), // 假定用户名需要去除前后空格
      level: form.level, // 角色筛选
      state: form.state// 状态筛选
    };
    // 调用API接口并传入筛选参数
    const result = await searchleader(queryParams);
    tableData.value = result.data.list;
  } catch (error) {
    console.error("查询过程中发生错误:", error);
    ElMessage.error("查询过程中发生错误，请检查网络或联系管理员。");
  }
};
const SearchClick = () => {
  searchleaderList();
};


//角色和状态转换
const roleMap = [
  { value: 1, label: "管理员" },
  { value: 2, label: "村级干部" },
  { value: 3, label: "乡级干部" },
  { value: 4, label: "县级干部" },
  { value: 5, label: "市级干部" },
  { value: 6, label: "省级干部" },
];
const stateMap = [
  { value: 0, label: "正常" },
  { value: 1, label: "停用" },
];
const formatState = (state) => {
  return state === 0 ? '正常' : '停用';
};

const formatLevel = (level) => {
  const role = roleMap.find(item => item.value === level);
  return role ? role.label : '';
};

//分页
const changePageNumber = (pageNum) => {
  form.pageNum = pageNum;
  myPage();
}

const handleSizeChange = () => {
  myPage();
}

const myPage = () => {
  area_data();
  searchPage(request_params).then((res) => {
    console.log(res)
    tableData.value = res.data.list;
    totalCount.value = res.data.total;
  });
}

//控制编辑对话框
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
//打开编辑对话框
const form1 = ref([])
const tableData1 = ref([])
const update=(index,row)=>{
  dialogFormVisible.value=true;
  tableData1.value =index
  form1.value =JSON.parse(JSON.stringify(row))
};
//确认编辑
const updateleader = async (clickState)=>{
  //调用接口
  let result = await leaderUpdateService(form1.value);
  location.reload();
  ElMessage.success(result.msg? result.msg:'编辑成功');
  //让对话框消失
  dialogFormVisible.value = false
}

const tableData2 = ref([])
//点击删除
const del=(index,row)=>{
  tableData1.value =index
  tableData2.value =JSON.parse(JSON.stringify(row))
};
//删除所选帮扶措施
const delLeader = async (clickState)=>{
  //调用接口
  let result = await leaderDelService(tableData2.value);
  location.reload();
  ElMessage.success(result.msg? result.msg:'删除成功');
}


import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {searchPage} from "@/api/farmer";
//控制抽屉是否显示
const visibleDrawer = ref(false)

//添加
const addleader = async (clickState)=>{
  //调用接口
  let result = await leaderAddService(leaderModel.value);
  location.reload();
  ElMessage.success(result.msg? result.msg:'添加成功');
  //让抽屉消失
  visibleDrawer.value = false;
}
const no = async (clickState)=>{
  //让抽屉消失
  visibleDrawer.value = false;
}

//状态+角色映射
onMounted(() => {
  // 初始化数据后，进行状态映射
  leaderModel.value.level = roleMap.find(item => item.value === leaderModel.value.level)?.value ?? '';
  if (form1.value) {
    form1.value.level = roleMap.find(item => item.value === form1.value.level)?.value ?? '';
  }

  form.state = stateMap.find(item => item.value === form.state)?.value ?? '';
  if (form1.value) {
    form1.value.state = stateMap.find(item => item.value === form1.value.state)?.value ?? '';
  }
  leaderModel.value.state = stateMap.find(item => item.value === leaderModel.value.state)?.value ?? '';
  searchleaderList(); // 获取数据
});


</script>

<style scoped>
/* 抽屉样式 */
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
:deep(.center-table td),
:deep(.center-table th) {
  text-align: center !important;
}

.page{
  margin-top:10px;
}
</style>